package helper

/**
                "code": "",
                "created_time": "2018-11-22 16:24:47",
                "desc": null,
                "finish_rate": "30/290",
                "finish_star": "4",
                "id": "73",
                "image": "",
                "level": "4",
                "lft": "146",
                "lib_type": "0",
                "ordering": "21",
                "path": "行测 > 数量关系",
                "pid": "72",
                "rgt": "159",
                "state": "1",
                "title": "数字推理",
                "updated_time": "2018-11-22 16:38:03"
 */
type Tree struct {
	Id int `json:"id"`
	Pid int `json:"pid"`
	Title string `json:"title"`
	Level string `json:"level"`
	Lft string `json:"lft"`
	Rgt string `json:"rgt"`
	Code string `json:"code"`
	Children []Tree `json:"children"`
	FinishRate string `json:"finish_rate"`
	FinishStar string `json:"finish_star"`
	Image string `json:"image"`
	LibType string `json:"lib_type"`
	Ordering string `json:"ordering"`
	Path string `json:"path"`
}

type ItemTree struct {
	Id int `json:"id"`

}

//var treedata  = map[int] []Tree{}
//func main(){
//	var trees []Tree
//	trees = append(trees,Tree{1,0,"root",nil})
//	trees = append(trees,Tree{2,1,"one.1",nil})
//	trees = append(trees,Tree{3,2,"one.1.1",nil})
//	trees = append(trees,Tree{4,1,"one.2",nil})
//	trees = append(trees,Tree{5,4,"one.2.1",nil})
//	trees = append(trees,Tree{6,4,"one.2.2",nil})
//	trees = append(trees,Tree{7,6,"one.2.2.1",nil})
//	f := tree(trees)
//	t,_ := json.Marshal(f)
//	log.Info("%s",string(t))
//}
type DeepTree struct{}
func (d DeepTree) Make(data []Tree,pid int) []Tree{
	//var final FinalTree
	var treedata  = map[int] []Tree{}
	for _,node := range data{
		treedata[node.Pid] = append(treedata[node.Pid],node)
	}
	return d.childTree(treedata,pid)
}

func (d DeepTree) childTree(td map[int][]Tree,pid int)[]Tree{
	if r,ok := td[pid];ok{
		for k,v := range r{
			if ft := d.childTree(td,v.Id);ft != nil{
				for _,vc := range ft{
					r[k].Children = append(r[k].Children,vc)
				}
			}else{
				r[k].Children = nil
			}
		}

		return r
	}
	return nil
}
